package com.cti.ftpservice.ftp;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.cti.ftpservice.utils.FtpWsManagerUtil;
import com.cti.ftpservice.vo.OnixBookBaseInfoVo;
import com.cti.ftpservice.vo.OnixSupplyBookInfoVo;

public class XmlReadHandler extends  DefaultHandler {

	 private List<OnixBookBaseInfoVo> bookBaseInfoVos;
	 
	 private static Log logger = LogFactory.getLog(XmlReadHandler.class);
	 
	 /**
	  * 已经解析并保存的数据
	  */
	 private int readySaveRecordCount;
	 
	 private Date lastUpdate;
	 
	 private int totalCount=0;
	 
	 private String currentQName;
	 
	 /**
	  * 
	  */
	 private String textTypeCode;
	 
	 private String isbnType;
	 
	 private String contributorRole;
	 
	 private String extentType;
	 
	 private OnixBookBaseInfoVo currentOnixBookBaseInfoVo;
	 
	 /**
	  * 当前供应商
	  */
	 private OnixSupplyBookInfoVo currentOnixSupplyBookInfoVo;
	
	 public XmlReadHandler(int _readySaveRecordCount,Date _lastUpdate) {
	        this.setReadySaveRecordCount(_readySaveRecordCount);
	        lastUpdate=_lastUpdate;
	  }
	 
	 public void startDocument () {  
		 bookBaseInfoVos=new ArrayList<OnixBookBaseInfoVo>();
	 }  
	  
	 public void endDocument () {
		 try {
			 logger.info("共解析："+bookBaseInfoVos.size()+"条数据");
		} catch (Exception e) {
			// TODO: handle exception
		}
			
	 }  
  
	@Override
	public void startElement(String uri, String localName, String qName,
            Attributes atts)  {
		try {
			currentQName=qName;
			if(totalCount<readySaveRecordCount)
				 return;
			//这时开始标签
			if(qName.equals("Product")||qName.equals("product")) {
				currentOnixBookBaseInfoVo=new OnixBookBaseInfoVo();
				currentOnixBookBaseInfoVo.setLastUpdateDate(lastUpdate);
			}
			if(qName.equals("Measure")||qName.equals("c094")) {
				if(currentOnixBookBaseInfoVo.getDimensions()==null)
					currentOnixBookBaseInfoVo.setDimensions("");
			}
			if(qName.equals("SupplyDetail")||qName.equals("supplydetail"))
				currentOnixSupplyBookInfoVo=new OnixSupplyBookInfoVo();
		} catch (Exception e) {
			logger.error("startElement:"+e.getMessage());
		}
	}

	
	 @Override
	public void characters(char[] ch, int start, int length)  throws SAXException{
		 try {
			 if(currentQName==null)
				 return;
			 if(totalCount<readySaveRecordCount)
				 return;
			 //解析到标签的值
			 String value = new String(ch, start, length); 
				switch (currentQName) {
				case "RecordReference":
				case "a001":
					if(value!=null)
						value=value.replace("-", "");
					currentOnixBookBaseInfoVo.setIsbn(value);
					break;
				case "b221":
					isbnType=value;
					break;
				case "b244":
					if(isbnType!=null&&isbnType.equals("15"))
						currentOnixBookBaseInfoVo.setIsbn(value);
					break;
				case "TitleText":
				case "b203":
					currentOnixBookBaseInfoVo.setTitle(value);
					break;
				case "Subtitle":
				case "b029":
					if(currentOnixBookBaseInfoVo.getSubTitle()==null)
						currentOnixBookBaseInfoVo.setSubTitle(value);
					else
						currentOnixBookBaseInfoVo.setSubTitle(currentOnixBookBaseInfoVo.getSubTitle()+value);
					break;
				case "TitleOfSeries":
					currentOnixBookBaseInfoVo.setSeriesTitle(value);
					break;
				case "LanguageCode":
				case "b252":
					currentOnixBookBaseInfoVo.setLanguage(value);
					break;
				case "IllustrationsNote":
				case "b062":
					currentOnixBookBaseInfoVo.setIllustration(value);
					break;
				case "b218":
					extentType=value;
					break;
				case "b219":
					if(extentType!=null&&(extentType.equals("05")||extentType.equals("00"))){
						currentOnixBookBaseInfoVo.setPageSize(value);
					}	
					break;
				case "NumberOfPages":
					currentOnixBookBaseInfoVo.setPageSize(value);
					break;
				case "SubjectSchemeIdentifier":
				case "b067":
					String mean=FtpWsManagerUtil.getSubjectSchemeIdentifierMean(value);
					if(currentOnixBookBaseInfoVo.getSubject()==null)
						currentOnixBookBaseInfoVo.setSubject(mean+":");
					else
						currentOnixBookBaseInfoVo.setSubject(currentOnixBookBaseInfoVo.getSubject()+mean+":");
					break;
				case "SubjectHeadingText":
				case "b070":
					if(currentOnixBookBaseInfoVo.getSubject()==null)
						currentOnixBookBaseInfoVo.setSubject(value+";");
					else
						currentOnixBookBaseInfoVo.setSubject(currentOnixBookBaseInfoVo.getSubject()+value+";");
					break;
				case "ContributorRole":
				case "b035":
					contributorRole=value;
					break;
				case "PersonName":
				case "b036":
					if(contributorRole.equals("A01")||contributorRole.equals("B01")){
						if(currentOnixBookBaseInfoVo.getAuthor()==null)
							currentOnixBookBaseInfoVo.setAuthor(value);
						else
							currentOnixBookBaseInfoVo.setAuthor(currentOnixBookBaseInfoVo.getAuthor()+value);
					}	
					break;
				case "PublisherName":
				case "b081":
					currentOnixBookBaseInfoVo.setPublisherName(value);
					break;
				case "CityOfPublication":
				case "b209":
				case "CountryOfPublication":
				case "b083":
					if(currentOnixBookBaseInfoVo.getPublishAddress()==null)
						currentOnixBookBaseInfoVo.setPublishAddress(value);
					else
						currentOnixBookBaseInfoVo.setPublishAddress(currentOnixBookBaseInfoVo.getPublishAddress()+","+value);
					break;
				case "PublicationDate":
				case "b306":
					currentOnixBookBaseInfoVo.setPublishDate(value);
					if(value.length()>4)
						currentOnixBookBaseInfoVo.setPublishYear(value.substring(0,4));
					break;
					
				case "MeasureTypeCode":
				case "x315":
					if(value.equals("01"))
						currentOnixBookBaseInfoVo.setDimensions(currentOnixBookBaseInfoVo.getDimensions()+"Height:");
					if(value.equals("02"))
						currentOnixBookBaseInfoVo.setDimensions(currentOnixBookBaseInfoVo.getDimensions()+"Width:");
					break;
				case "Measurement":
				case "c094":
					currentOnixBookBaseInfoVo.setDimensions(currentOnixBookBaseInfoVo.getDimensions()+value+"");
					break;
				case "MeasureUnitCode":
				case "c095":
					currentOnixBookBaseInfoVo.setDimensions(currentOnixBookBaseInfoVo.getDimensions()+value+";");
					break;
				case "TextTypeCode":
				case "TextType":
					textTypeCode=value;
					break;
				case "Text":
					if(textTypeCode.equals("03")){
						if(currentOnixBookBaseInfoVo.getDescription()!=null)
							currentOnixBookBaseInfoVo.setDescription(currentOnixBookBaseInfoVo.getDescription()+value);
						else
							currentOnixBookBaseInfoVo.setDescription(value);
					}	
					break;
				case "SupplierName":
				case "j137":
						currentOnixSupplyBookInfoVo.setSupplyName(value);
					break;
				case "PriceAmount":
				case "j151":
					currentOnixSupplyBookInfoVo.setPrice(Double.parseDouble(value));
					break;
				case "CurrencyCode":
				case "j152":
					currentOnixSupplyBookInfoVo.setCurrency(value);
					break;
				case "TaxRatePercent1":
					currentOnixSupplyBookInfoVo.setTaxRatePercent(Double.parseDouble(value));
					break;
				case "TaxableAmount1":
					currentOnixSupplyBookInfoVo.setTaxableAmount(Double.parseDouble(value));
					break;
				case "TaxAmount1":
					currentOnixSupplyBookInfoVo.setTaxAmount(Double.parseDouble(value));
					break;
				default:
					break;
				} 
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	 
		
	@Override
	public void endElement (String uri, String localName, String qName)  
	{
		try {
			//这是结束标签
			if(qName.equals("Product")||qName.equals("product")){
				totalCount++;
			}
			if(totalCount>readySaveRecordCount){
				if(qName.equals("Product")||qName.equals("product"))
					bookBaseInfoVos.add(currentOnixBookBaseInfoVo);
				if(qName.equals("SupplyDetail")||qName.equals("supplydetail"))
					currentOnixBookBaseInfoVo.getSupplyinfos().add(currentOnixSupplyBookInfoVo);
			}
			currentQName=null;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	} 
	
	 public  InputSource resolveEntity (String publicId,
              String systemId){
		 if(publicId==null)
			 return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='GBK'?>".getBytes()));
		 else
			 return null;
	  }
	 
	public int getReadySaveRecordCount() {
		return readySaveRecordCount;
	}

	public void setReadySaveRecordCount(int readySaveRecordCount) {
		this.readySaveRecordCount = readySaveRecordCount;
	}

	public List<OnixBookBaseInfoVo> getBookBaseInfoVos() {
		return bookBaseInfoVos;
	}

	public void setBookBaseInfoVos(List<OnixBookBaseInfoVo> bookBaseInfoVos) {
		this.bookBaseInfoVos = bookBaseInfoVos;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public Date getLastUpdate() {
		return lastUpdate;
	}

	public void setLastUpdate(Date lastUpdate) {
		this.lastUpdate = lastUpdate;
	}

}
